package cn.yunhe.service.impl;

import cn.yunhe.dao.IUserInfoDao;
import cn.yunhe.pojo.ResultRequest;
import cn.yunhe.pojo.Role;
import cn.yunhe.pojo.UserInfo;
import cn.yunhe.service.IUserInfoService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("userService")
public class UserInfoServiceImpl implements IUserInfoService {

    @Autowired
    IUserInfoDao userInfoDao;

    /**
     * 加载用户信息封装到User对象中
     * @param userName
     * @return UserDetails
     *  UserDetails是接口，给了一个实现类User中包含了所有需要的用户的信息，
     *  此处返回一个User对象即可
     * @throws UsernameNotFoundException
     */
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        //根据用户名获取到用户信息
        UserInfo userInfo = userInfoDao.queryUserInfo(userName);
        //创建user对象返回
        /**
         * String username, 用户名
         * String password, 密码
         * boolean enabled, 是否可用
         * boolean accountNonExpired, 账户是否过期
         * boolean credentialsNonExpired, 账户身份认证是否过期
         * boolean accountNonLocked, 账户是否被锁定
         * Collection<? extends GrantedAuthority> authorities 当该账户认证成功了之后应该被授予哪些权限
         */
        User user = new User(userInfo.getUsername(),
                "{noop}"+userInfo.getPassword(),
                userInfo.getStatus()==1?true:false,
                true,true,true,
                getAuthority(userInfo.getRoles()));
        return user;
    }

    /**
     * 目的：查到指定用户对应的所有的角色信息，将其添加到Collection<? extends GrantedAuthority> authorities
     * 因为SpringSecurity会通过authorities去对角色进行认证
     * @param roleList
     *  从数据库查询出来的用户对应的角色列表
     *  ArrayList<SimpleGrantedAuthority> 存储用户的角色给SpringSecurity进行认证
     * @return
     */
    public List<SimpleGrantedAuthority> getAuthority(List<Role> roleList){
        ArrayList<SimpleGrantedAuthority> simpleGrantedAuthorities = new ArrayList<SimpleGrantedAuthority>();
        for(Role role : roleList){
            simpleGrantedAuthorities.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName()));
        }
        return  simpleGrantedAuthorities;
    }

    public List<UserInfo> queryAll(ResultRequest resultRequest) {
        PageHelper.startPage(resultRequest.getPage(), resultRequest.getLimit());
        return userInfoDao.queryAll();
    }
}
